package com.mijie.homi.search.util;

import java.io.IOException;
import java.io.Reader;////
//import mapper.AnnUsersMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SessionFactory {
	private static String RESOURCE = "/ibatisContext.xml";
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

	public static SqlSessionFactory getSessionFactory() {
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(RESOURCE);
		} catch (IOException e) {
			System.out.println("read mybatis-config.xml failed!");
			e.printStackTrace();
		}
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
				.build(reader);
		Configuration config = sessionFactory.getConfiguration();
		// config.addMapper(AnnUsersMapper.class);
		return sessionFactory;
	}

	public static SqlSession getSession() {
		SqlSession session = threadLocal.get();
		if (session == null) {
			session = getSessionFactory().openSession();
			threadLocal.set(session);
			return session;
		}
		return session;
	}

	public static void closeSession() {
		SqlSession session = threadLocal.get();
		if (session != null) {
			threadLocal.set(null);
			session.close();
		}
	}
}